#!/usr/bin/env node

/**
 * 代理清理测试脚本
 * 用于验证代理设置和清理功能是否正常工作
 */

import { EnhancedSystemProxyManager } from "../src/proxy/enhanced-system-proxy.js";
import https from 'https';
import http from 'http';

console.log("🧪 代理清理测试工具");
console.log("===================\n");

const proxyManager = new EnhancedSystemProxyManager('localhost', 12300);

async function testHttpsConnection(url = 'https://www.baidu.com') {
  return new Promise((resolve) => {
    console.log(`🔗 测试HTTPS连接: ${url}`);
    
    const startTime = Date.now();
    const request = https.get(url, { timeout: 10000 }, (res) => {
      const duration = Date.now() - startTime;
      console.log(`✅ HTTPS连接成功: ${res.statusCode} (${duration}ms)`);
      resolve(true);
    });

    request.on('error', (error) => {
      const duration = Date.now() - startTime;
      console.log(`❌ HTTPS连接失败: ${error.message} (${duration}ms)`);
      resolve(false);
    });

    request.on('timeout', () => {
      const duration = Date.now() - startTime;
      console.log(`⏱️ HTTPS连接超时 (${duration}ms)`);
      request.destroy();
      resolve(false);
    });
  });
}

async function testProxyCleanup() {
  try {
    console.log("📋 第1步: 检查初始状态");
    const initialStatus = await proxyManager.getProxyStatus();
    console.log("初始代理状态:", initialStatus);
    
    if (initialStatus.enabled) {
      console.log("\n📋 第2步: 测试HTTPS连接 (代理启用状态)");
      await testHttpsConnection();
      
      console.log("\n📋 第3步: 执行代理清理");
      const cleanupSuccess = await proxyManager.restoreSystemProxy();
      console.log(`代理清理结果: ${cleanupSuccess ? '成功' : '失败'}`);
      
      console.log("\n📋 第4步: 验证清理后状态");
      const afterCleanupStatus = await proxyManager.getProxyStatus();
      console.log("清理后代理状态:", afterCleanupStatus);
      
      console.log("\n📋 第5步: 测试HTTPS连接 (代理清理后)");
      const httpsWorking = await testHttpsConnection();
      
      if (httpsWorking) {
        console.log("\n✅ 测试通过: 代理清理成功，HTTPS连接正常");
      } else {
        console.log("\n❌ 测试失败: 代理清理后HTTPS连接仍然有问题");
        
        console.log("\n📋 第6步: 尝试应急恢复");
        const emergencySuccess = await proxyManager.emergencyRestore();
        console.log(`应急恢复结果: ${emergencySuccess ? '成功' : '失败'}`);
        
        console.log("\n📋 第7步: 再次测试HTTPS连接");
        const finalTest = await testHttpsConnection();
        
        if (finalTest) {
          console.log("\n✅ 应急恢复成功: HTTPS连接恢复正常");
        } else {
          console.log("\n❌ 应急恢复失败: 需要手动清理系统代理");
          proxyManager.printManualRestoreGuide();
        }
      }
      
    } else {
      console.log("\n📋 第2步: 测试HTTPS连接 (无代理状态)");
      const httpsWorking = await testHttpsConnection();
      
      if (httpsWorking) {
        console.log("\n✅ 系统正常: 无代理状态下HTTPS连接正常");
      } else {
        console.log("\n❌ 系统异常: 无代理状态下HTTPS连接失败");
        console.log("可能的原因:");
        console.log("1. 网络连接问题");
        console.log("2. DNS解析问题");
        console.log("3. 防火墙阻止");
        console.log("4. 系统代理设置残留");
      }
    }
    
  } catch (error) {
    console.error("❌ 测试过程中发生错误:", error.message);
  }
}

async function main() {
  console.log("开始代理清理测试...\n");
  
  await testProxyCleanup();
  
  console.log("\n测试完成！");
}

// 添加进程退出处理
process.on("SIGINT", () => {
  console.log("\n👋 测试工具已退出");
  process.exit(0);
});

process.on("uncaughtException", (error) => {
  console.error("\n❌ 发生未预期的错误:", error.message);
  process.exit(1);
});

// 运行测试
main(); 